<?php
namespace App\Http\Library;

//2种获取快递信息的方法（有curl扩展和没有crul）,如果你有curl扩展可以只复制kuaidi100这个类，没有就全部复制
use Exception;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Kuaidi100
{
    public $kuaidi100key = 'ofroiXta229'; //快递100的key

    public $url = 'https://poll.kuaidi100.com/poll/query.do';

    public $customer = "72AE681BC75945BAF19EDD416EBE2C82";

    public $company = "顺丰速运";


    public function __construct($config = []){
        if(isset($config['key'])&&$config['key']){
            $this->kuaidi100key = $config['key'];
        }
        if(isset($config['customer'])&&$config['customer']){
            $this->customer = $config['customer'];
        }
        if(isset($config['company'])&&$config['company']){
            $this->company = $config['company'];
        }
    }



    /**
     * @throws Exception
     */
    public function get($getNu, $com = null){
        $postcom = $this->getcom($com?:$this->company);
        $sign = $this->sign($postcom,$getNu);
        $params = [
            'customer'=>$this->customer,
            'param'=>'{"com":"'.$postcom.'","num":"'.$getNu.'"}',
            'sign'=>$sign
        ];
        try {
            $res = self::curlPost($this->url, $this->setDataStr($params));
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        return $res;
    }

    public function sign($com,$num){
        $customer = $this->customer;
        $key = $this->kuaidi100key;
        $param = '{"com":"'.$com.'","num":"'.$num.'"}';
        return strtoupper(md5($param.$key.$customer));
    }

    public function setDataStr($data){
        $str = "";
        foreach ($data as $key => $value) {
            $str.= "$key=".urlencode($value)."&";
        }
        $str = substr($str,0,-1);
        return $str;
    }


    public function getcom($com){
        $title = array_column(config('platform.company'),'title');
        $value = array_column(config('platform.company'),'value');
        $company = array_combine($title, $value);
        return $company[$com];
    }

    public static function curlPost($url, $post_data){
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        return json_decode($result,JSON_UNESCAPED_UNICODE);
    }


}
